package com.example.canteen.service;

import com.example.canteen.converter.UserConverter;
import com.example.canteen.dao.User;
import com.example.canteen.dao.UserRepository;
import com.example.canteen.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;

    @Override
    public Set<UserDTO> getAllUsers() {
        return userRepository.findAll().stream().map(UserConverter::convertUser).collect(Collectors.toSet());
    }

    @Override
    public UserDTO getUserByName(String username) {
        return UserConverter.convertUser(userRepository.findByUsername(username));
    }

    @Override
    public Map<String, Object> login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        } else {
            Map<String, Object> responseData = new HashMap<>();
            if (!password.equals(user.getPassword())) {
                return responseData;
            }
            responseData.put("id", user.getId());
            responseData.put("type", user.getType());
            responseData.put("department", user.getDepartment());
            return responseData;
        }
    }

    @Override
    public Long register(UserDTO userDTO) {
        if (userRepository.findByUsername(userDTO.getUsername()) != null) {
            throw new RuntimeException("用户已存在");
        }
        if (userDTO.getType() == null) {
            userDTO.setType(User.UserType.GUEST);
        }
        return userRepository.save(UserConverter.convertUser(userDTO)).getId();
    }

    @Override
    public UserDTO updateUserById(Long id, String name, String password, User.UserType type,String department) {
        User userInDB = userRepository.findById(id).orElseThrow(() -> new RuntimeException("用户不存在"));
        if (StringUtils.hasLength(name) && !name.equals(userInDB.getUsername())) {
            userInDB.setUsername(name);
        }
        if (StringUtils.hasLength(password) && !password.equals(userInDB.getPassword())) {
            userInDB.setPassword(password);
        }
        if (StringUtils.hasLength(department) && !department.equals(userInDB.getDepartment())) {
            userInDB.setDepartment(department);
        }
        if (type != null && type != userInDB.getType()) {
            userInDB.setType(type);
        }
        return UserConverter.convertUser(userRepository.save(userInDB));
    }

    @Override
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }
}
